<?php

namespace App\Http\Services\FormBuilder\Elements;

class RadioButton extends Checkbox
{
    public $fillable = [
        'id', 'name', 'type','class','value','checked'
    ];

    protected $attributes = [
        'type' => 'radio',

    ];

    public function __construct($name, $value = null)
    {
        parent::__construct($name);

        if (is_null($value)) {
            $value = $name;
        }

        $this->setValue($value);
    }

    public function render()
    {
        if ($this->label) {
            $element        = clone $this;
            $element->label = false;

            return (new Field(new RadioButtonWrapper($element, $this->label)))->render();
        }

        $result = '<input';

        $result .= $this->renderAttributes();

        $result .= '>';

        return $result;
    }

    public function editBlock()
    {
        //dd($this);
        $outLabel = (new Label($this->getAttribute('display_name')))
            ->addClass('d-block')
            ->forId($this->getAttribute('id'))
            ->required((int) $this->getAttribute('require'));

        $tips = (new HelpBlock($this->getAttribute('tips')));
        $fields = '';
        $li_class = $this->getAttribute('li_class');
        $name = $this->getAttribute('name');
        $options = $this->getAttribute('options');
        $value = $this->getAttribute('value');
        $value = $value['value']?:'';

        foreach ($options as $key=>$v)
        {
            $label = (new Label($v))
                ->addClass('custom-control-label font-w400')
                ->forId('radio-custom-inline_'.$key.'_'.$name);

            if ($value == $key) {
                $this->setAttribute('checked',true);
            } else {
                $this->removeAttribute('checked');
            }

            $this->setAttribute('id','radio-custom-inline_'.$key.'_'.$name);
            $this->setAttribute('class','custom-control-input');
            $this->setValue($key);
            $div = (new Field($this,$label))
                ->addClass('custom-control custom-radio custom-control-inline custom-control-primary');
            $div->setAttribute('style','margin-top: 5px;');
            $fields .= $div->render();
        }

        $html = '<div class="'.$li_class.'" style="padding: 10px;">';
        $html .= $outLabel;
        $html .= $fields;
        $html .= $tips;
        $html .= '</div>';

        return $html;
    }

    public function detailBlock()
    {
        $class = $this->getAttribute('li_class');
        $displayName = $this->getAttribute('display_name');
        $value = $this->getAttribute('value');
        if (is_array($value)) {
            $value = $value['value'];
        }
        $html = '';
        $html .= '<div class="items '.$class.'">';
        $html .= '<label class="col-12">'.$displayName.'</label>&nbsp';
        $html .= '<div class="detail col-4">'.$value.'</div>';
        $html .='</div>';

        return $html;
    }
}
